package com.mengniu.commerce.collect.third.request;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mengniu.commerce.collect.model.item.YzItem;
import com.mengniu.commerce.collect.third.YouZanApi;
import com.mengniu.commerce.collect.util.RestTemplateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindException;

import javax.annotation.Resource;

@Service
@Slf4j
public class IYouZanGoodsRequest {


    private static String baseUrl = "https://open.youzanyun.com";

    @Resource
    private RestTemplateUtil restTemplateUtil;


    public String getToken() {
        return restTemplateUtil.getToken();
    }

    /**
     * https://doc.youzanyun.com/detail/API/0/2783
     * 查询单商品明细接口-推荐使用
     *
     * @param bosId
     * @param goodsId 商品id
     */
    public YzItem getYzGoodsDetail(Long bosId, Long goodsId)  {
        YzItem yzItem = new YzItem();
        try {
            String token = this.getToken();
            String url = baseUrl + YouZanApi.YZ_GET_ITEM_DETAIL + "?access_token="+token;
            JSONObject js = new JSONObject();
            js.put("item_id", goodsId);
            JSONObject jsonObject = restTemplateUtil.doPost(js, url);
            System.out.println("商品详情结果-->"+jsonObject.toJSONString());
            if (!jsonObject.getInteger("code").equals(200) && !jsonObject.getBoolean("success") ){
                log.error("调用有赞查询商品详情接口失败_{}",JSONObject.toJSONString(jsonObject));
                throw new BindException(jsonObject,"调用有赞查询商品详情接口返回失败");
            }
            //商品返回对象
             yzItem = jsonObject.getObject("data", YzItem.class);
            log.info("getYzGoodsDetail_返回商品性情为_{}", JSON.toJSONString(yzItem));
        } catch (BindException e) {
            throw new RuntimeException(e);
        }
        return yzItem;
    }
}
